package 可视化算法.概率模拟算法.分钱游戏;

import javax.swing.*;
import java.awt.*;

/**
 * @author MT
 * <p>
 * <p>
 * 视图层
 * @date 2019-11-28 14:30
 */
public class AlgoFrame extends JFrame {

    private int canvasWidth;

    private int canvasHeight;

    public int getCanvasWidth() {
        return canvasWidth;
    }

    public int getCanvasHeight() {
        return canvasHeight;
    }

    public AlgoFrame(String title, int canvasWidth, int canvasHeight) {
        super(title);

        // 传入宽和高，只提供获取方法，不允许修改
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        // 创建画布
        AlgoCanvas canvas = new AlgoCanvas();
        // 设置窗口的内容面板
        this.setContentPane(canvas);
        this.pack();

        // 设置自己的默认窗口
        this.setSize(canvasWidth, canvasHeight);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public AlgoFrame(String tilte) {
        // 设置传入的标题和默认1024的宽和高
        this(tilte, 1024, 1024);
    }

    private int[] money;

    public void render(int[] money) {
        this.money = money;
        this.repaint();
    }

    private class AlgoCanvas extends JPanel {

        public AlgoCanvas() {
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g;

            // TODO: 2019-11-28 抗锯齿
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.addRenderingHints(hints);

            // TODO: 2019-11-29 具体的绘制
            int w = canvasWidth / money.length;
            for (int i = 0; i < money.length; i++) {
                if (money[i] > 0){
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Blue);
                    AlgoVisHelper.fillRectangle(g2d, i * w + 1, canvasHeight/2 - money[i], w - 1, money[i]);
                }else if (money[i] < 0){
                    AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);
                    AlgoVisHelper.fillRectangle(g2d, i * w + 1, canvasHeight/2, w - 1, -money[i]);
                }

            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(canvasWidth, canvasHeight);
        }
    }

}
